package com.example.ffepeg.ffeAdder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;

public class VideoMerger {

    public static void main(String[] args) {
        // 视频文件URL列表
        List<String> videoUrls = List.of(
                "https://pushimg.liecaizhijia.com/video/gen/2024-12-16/c23aa337-0f03-4690-9b8b-9a65770b7d88.mp4",
                "https://pushimg.liecaizhijia.com/video/gen/2024-12-16/40154397-47a9-42b2-a6fa-47219711f0de.mp4",
                "https://pushimg.liecaizhijia.com/video/gen/2024-12-16/3e3841b7-4f14-489c-9ab1-46f538ab9ac6.mp4",
                "https://pushimg.liecaizhijia.com/video/gen/2024-09-24/89a32ab1-3657-4e56-a83f-bda21593f817.mp4",
                "https://pushimg.liecaizhijia.com/video/gen/2024-12-16/d57bf06a-a1a9-4e0c-80bb-7a92ccca5edd.mp4"
        );

        // 输出文件路径
        String outputFile = "D:\\javaXM\\FFEpeg\\src\\main\\resources\\out\\twoSixfiles00k.mp4";

        // 临时文件夹路径
        Path tempDir = Paths.get("D:\\javaXM\\FFEpeg\\temp");
        if (!Files.exists(tempDir)) {
            try {
                Files.createDirectories(tempDir);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }

        // 视频列表文件路径
        Path listFile = Paths.get("D:\\javaXM\\FFEpeg\\src\\main\\resources\\filelist.txt");

        // 下载视频并创建视频列表文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(listFile.toFile()))) {
            for (String videoUrl : videoUrls) {
                Path tempVideoFile = downloadVideo(videoUrl, tempDir);
                writer.write("file '" + tempVideoFile.toAbsolutePath().toString() + "'\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 构建FFmpeg命令
        String ffmpegCmd = "ffmpeg -f concat -safe 0 -i " + listFile.toAbsolutePath() + " -c copy " + outputFile;

        // 执行FFmpeg命令
        try {
            Process process = Runtime.getRuntime().exec(ffmpegCmd);
            process.waitFor();
            System.out.println("视频合并完成!");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static Path downloadVideo(String url, Path destinationDir) throws IOException {
        URL videoUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) videoUrl.openConnection();
        Path tempFile = Files.createTempFile(destinationDir, UUID.randomUUID().toString(), ".mp4");

        try (InputStream in = connection.getInputStream()) {
            Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING);
        }

        return tempFile;
    }
}
